/*
 * @lc app=leetcode.cn id=54 lang=swift
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
class Solution {
    func spiralOrder(_ matrix: [[Int]]) -> [Int] {
        if matrix.count == 0 {
            return []
        }

        /// 边界
        var left = 0
        var right = matrix[0].count - 1
        var top = 0
        var bottom = matrix.count - 1

        /// 总数
        var totalCount = (right + 1) * (bottom + 1)

        var result = [Int]()


        while totalCount >= 1 {

            /// 从左到右遍历
            var i = left
            while i <= right,totalCount>=1 {
                result.append(matrix[top][i])
                totalCount -= 1
                i += 1
            }


            top += 1

            /// 从上到下
            i = top
            while i <= bottom,totalCount>=1 {
                result.append(matrix[i][right])
                totalCount -= 1
                i += 1
            }

            right -= 1

            /// 从右 到 左
            i = right
            while i >= left,totalCount>=1 {
                result.append(matrix[bottom][i])
                totalCount -= 1
                i -= 1
            }

            bottom -= 1

            /// 从 下 到上
            i = bottom
            while i >= top,totalCount>=1 {
                result.append(matrix[i][left])
                totalCount -= 1
                i -= 1
            }

            left += 1
        }

        return result
    }
}
// @lc code=end

